<template>
  <view class="test">
    <span @click="upload">上传图片</span>
    <view v-for="(item,index) in info.img" :key="index">
      <image :src="item" mode=""></image>
    </view>
  </view>
</template>

<script setup>
  import {
    reactive,
    getCurrentInstance
  } from 'vue'
  import {
    fileName
  } from '@/utils/formatDate.js'
  const info = reactive({
    id: 'dsadasd',
    img: [], //图片数组
  })
  const instance = getCurrentInstance()
  //文件、图片上传
  function upload() {
    let url = fileName(new Date()) //当前日期文件夹
    uni.chooseImage({
      count: 9, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册|拍照选择
      success: (chooseImageRes) => {
        const tempFilePaths = chooseImageRes.tempFilePaths;
        console.log('tempFilePaths', tempFilePaths)
        //实现多张图片逐一上传
        for (let i = 0; i < tempFilePaths.length; i++) {
          const uploadTask = uni.uploadFile({
            url: `${instance.proxy.serverUrl}/files/upload`, //仅为示例，非真实的接口地址[后端接口地址]
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              url: url,
              name: new Date().getTime() + info.id + i
            },
            success: (uploadFileRes) => {
              console.log(uploadFileRes);
              let path = instance.proxy.serverUrl + uploadFileRes.data
              info.img.push(path)
            }
          });
          uploadTask.onProgressUpdate((res) => {
            console.log('上传进度' + res.progress);
            console.log('已经上传的数据长度' + res.totalBytesSent);
            console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

            // 测试条件，取消上传任务。
            // if (res.progress > 50) {
            //   uploadTask.abort();
            // }
          });
        }
      }
    });
  }
</script>

<style lang="scss">
  .test {
    margin: 150rpx;
    text-align: center;
    font-size: 40rpx;
  }
</style>
